package com.easemob.helpdesk.utils;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
//<<<<<<< HEAD
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.widget.Toast;
//=======
import android.util.ArraySet;
import android.util.Log;
//>>>>>>> master-temp

import androidx.core.app.NotificationCompat;

import com.easemob.helpdesk.activity.ChatActivity;
import com.easemob.helpdesk.activity.MainActivity;
import com.easemob.helpdesk.emoticon.utils.SimpleCommonUtils;
import com.easemob.helpdesk.recorder.MediaManager;
import com.housekeeperapp.MainApplication;
import com.housekeeperapp.R;
import com.hyphenate.kefusdk.HDDataCallBack;
//import com.hyphenate.kefusdk.bean.HDSession;
import com.hyphenate.kefusdk.chat.HDClient;
//import com.hyphenate.kefusdk.entity.HDImageMessageBody;
import com.hyphenate.kefusdk.entity.HDMessage;
//import com.hyphenate.kefusdk.entity.HDMessageUser;
//import com.hyphenate.kefusdk.entity.HDNormalFileMessageBody;
//import com.hyphenate.kefusdk.entity.HDTextMessageBody;
//import com.hyphenate.kefusdk.entity.HDVideoMessageBody;
//import com.hyphenate.kefusdk.entity.HDVoiceMessageBody;
import com.hyphenate.kefusdk.entity.HDSession;
import com.hyphenate.kefusdk.entity.user.HDMessageUser;
import com.hyphenate.kefusdk.gsonmodel.customer.CustomerInfoResponse;
import com.hyphenate.kefusdk.manager.session.CurrentSessionManager;
import com.hyphenate.kefusdk.messagebody.HDImageMessageBody;
import com.hyphenate.kefusdk.messagebody.HDNormalFileMessageBody;
import com.hyphenate.kefusdk.messagebody.HDTextMessageBody;
import com.hyphenate.kefusdk.messagebody.HDVideoMessageBody;
import com.hyphenate.kefusdk.messagebody.HDVoiceMessageBody;
import com.hyphenate.kefusdk.utils.HDLog;
import com.liyuzhao.badger.BadgeUtil;
import com.reactnativenavigation.controllers.NavigationCommandsHandler;

import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HDNotifier {
	
	private final static String TAG = HDNotifier.class.getSimpleName();
	
	static Ringtone ringtone = null;
	
	private final static String msg_eng = "receive message!";
	

	public static int notifyID = 1314;//start notification id
	
	private NotificationManager notificationManager = null;
	
	private int notificationNum = 0;
	//适配android 8.0
	private static String channelId = "1";
	private static String channelName = "管家官网渠道";
	
	private Context appContext;
	
	private String appName;
	private String packageName;
	private String msgs;
	private long lastNotifyTime;
	
	private static HDNotifier instance;
	
	private AudioManager audioManager;
	private Vibrator vibrator;

	private SoundPool mSoundPlayer;
	float volume;
	
	private ExecutorService notifierThread = Executors.newSingleThreadExecutor();
	
	private HDNotifier(Context context){
		appContext = context;
		if(notificationManager == null){
			notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		}
		
		if(appContext.getApplicationInfo().labelRes != 0){
			appName = appContext.getString(appContext.getApplicationInfo().labelRes);
		}else{
			appName = "";
		}
		
		packageName = appContext.getApplicationInfo().packageName;
//		if(Locale.getDefault().getLanguage().equals("zh")){
//			
//		}else{
//			
//		}
		msgs = "您有一条新消息";

		audioManager = (AudioManager) appContext.getSystemService(Context.AUDIO_SERVICE);
		vibrator = (Vibrator) appContext.getSystemService(Context.VIBRATOR_SERVICE);
		
	}
	
	public static HDNotifier getInstance(){
		if(instance == null){
			synchronized (HDNotifier.class){
				if(instance == null){
					instance = new HDNotifier(MainApplication.getInstance());
				}
			}
		}
		return instance;
	}
	
	
	public void stop(){
		if(ringtone != null){
			ringtone.stop();
			ringtone = null;
		}
	}
	

	private void sendNotifaction(HDMessage message){

		PackageManager packageManager = appContext.getPackageManager();

		//notification title

		//create and send notification
		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
			NotificationChannel channel = new NotificationChannel(channelId,channelName,NotificationManager.IMPORTANCE_DEFAULT);
			notificationManager.createNotificationChannel(channel);
			mBuilder.setChannelId(channelId);
		}
		mBuilder.setSmallIcon(appContext.getApplicationInfo().icon);
//		mBuilder.setLargeIcon(BitmapFactory.decodeResource(appContext.getResources(), R.drawable.icon_launcher2));
		mBuilder.setWhen(System.currentTimeMillis());
		mBuilder.setAutoCancel(true);

		mBuilder.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
			mBuilder.setColor(Color.GRAY);
		} else {
			mBuilder.setColor(Color.TRANSPARENT);
		}

		Intent msgIntent = appContext.getPackageManager().getLaunchIntentForPackage(packageName);
		msgIntent.putExtra("is_from_click_notification",true);

		HDMessageUser user = null;
		if(message!=null){
			msgIntent.putExtra("hasUnReadMessage", true);
			msgIntent.putExtra("visitorid", message.getSessionServiceId());

			HDSession session = CurrentSessionManager.getInstance()
					.getSessionEntity(message.getSessionServiceId());

			if (session != null && MainActivity.instance != null) {
				msgIntent.setClass(appContext, ChatActivity.class);

				System.out.println("HDSession is " + session.getUser().getNicename());

				msgIntent.putExtra("user", session.getUser());
				msgIntent.putExtra("originType",session.getOriginType());
				msgIntent.putExtra("techChannelName", session.getTechChannelName());
				msgIntent.putExtra("chatGroupId", session.getChatGroupId());

				if(!CommonUtils.isBlank(session.getUser().getUsername())){
					msgIntent.putExtra("truename", session.getUser().getUsername());
				}else{
					msgIntent.putExtra("truename", session.getUser().getNicename());
				}

				msgIntent.putExtra("user_phone", "");
				msgIntent.putExtra("username", "");

				user = session.getUser();
			} else {
				System.out.println("HDSession is null");
//				this.mAction = o.mAction;
//				this.mData = o.mData;
//				this.mType = o.mType;
//				this.mPackage = o.mPackage;
//				this.mComponent = o.mComponent;
//				if (o.mCategories != null) {
//					this.mCategories = new ArraySet<String>(o.mCategories);
//				}

				msgIntent.setAction(Intent.ACTION_MAIN);
				msgIntent.addCategory(Intent.CATEGORY_LAUNCHER);
				msgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				msgIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				msgIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
				msgIntent.putExtra("user", message.getFromUser());
				user = message.getFromUser();
			}
		}

		PendingIntent pendingIntent = PendingIntent.getActivity(appContext, notifyID, msgIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		mBuilder.setContentTitle(packageManager.getApplicationLabel(appContext.getApplicationInfo()));
		if(user == null){
			mBuilder.setTicker(msgs);
			mBuilder.setContentText(msgs);
		}else{
			String sendMsg = "";
			if (message.getBody() instanceof HDVoiceMessageBody) {
				sendMsg = "[语音]";
			} else if (message.getBody() instanceof HDImageMessageBody) {
				sendMsg = "[图片]";
			} else if (message.getBody() instanceof HDNormalFileMessageBody) {
				sendMsg = "[文件]";
			} else if (message.getBody() instanceof HDVideoMessageBody) {
				sendMsg = "[视频]";
			} else if (message.getBody() instanceof HDTextMessageBody) {
				sendMsg = CommonUtils.convertStringByMessageText(((HDTextMessageBody) message.getBody()).getMessage());
			}

			mBuilder.setTicker(user.getNicename() + ": " + sendMsg);
			mBuilder.setContentText(user.getNicename() + ": " + sendMsg);
		}

		mBuilder.setContentIntent(pendingIntent);
		Notification notification = mBuilder.build();

//		try{
//			Field field = notification.getClass().getDeclaredField("extraNotification");
//			Object extraNotification = field.get(notification);
//			Method method = extraNotification.getClass().getDeclaredMethod("setMessageCount", int.class);
//			int unreadcount = HDApplication.getInstance().getUnReadMsgCount();
//			method.invoke(extraNotification, unreadcount);
//		}catch (Exception e){
//		}

		try {
			notificationManager.cancel(notifyID);
		} catch (Exception ignored) {
		}

		int count = MainApplication.getInstance().getUnReadMsgCount();
		try{
			HDLog.e(TAG, "send notification!!!!!!");
			BadgeUtil.sendBadgeNotification(notification, notifyID, appContext, count, count);
		}catch (Exception e){
			HDLog.e(TAG, "send notification error" + e.getMessage());
		}

		notificationManager.notify(notifyID, notification);
	}
	
	public synchronized void notifiChatMsg(HDMessage message){

		if (!MainApplication.getInstance().isNewMsgNotiStatus()) {
			return;
		}

		if (!CommonUtils.isAppRunningForeground2(appContext)){

			sendNotifaction(message);
		}
		notifyOnNewMsg();
	}


	public synchronized void notifiNewMsg(){

		if (!MainApplication.getInstance().isNewMsgNotiStatus()) {
			return;
		}

//		notifyOnNewMsg();
	}
	
	
	public void notifyOnNewMsg() {
		try {
			lastNotifyTime = System.currentTimeMillis();

			// 判断是否处于静音模式
			if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
				HDLog.e(TAG, "in slient mode now");
				return;
			}

//			if(vibrator.hasVibrator()){
//
//			}

			if (MainApplication.getInstance().isNotiAlertVibrateStatus()) {
				vibrator.cancel();

				//震动
				long[] pattern = new long[] { 0, 180, 80, 120 };
				vibrator.vibrate(pattern, -1);
			}

			if (!MainApplication.getInstance().isNotiAlertSoundStatus()) {
				return;
			}


			if(mSoundPlayer != null){
				mSoundPlayer.release();
				mSoundPlayer = null;
			}

			TelephonyManager telephonyManager = (TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE);
			volume = 0.1f;
			if (MediaManager.isPlaying() || TelephonyManager.CALL_STATE_OFFHOOK==telephonyManager.getCallState()||TelephonyManager.CALL_STATE_RINGING==telephonyManager.getCallState()){
				Log.d(TAG, "test media playing = onReceive: media playing is playing");
			}else {
				volume = 1.0f;
				volume = 1.0f;
			}

			mSoundPlayer = new SoundPool(10,
					AudioManager.STREAM_MUSIC, 5);
			mSoundPlayer.load(appContext, R.raw.new_msg_sound, 1);
			mSoundPlayer.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
				@Override
				public void onLoadComplete(SoundPool soundPool, int sampleId,
										   int status) {
					mSoundPlayer.play(1, volume, volume, 0, 0, 1);
				}
			});


//			String vendor = Build.MANUFACTURER;
//			if (ringtone == null) {
//				Uri cus_notification = Uri.parse("android:resource://"+appContext.getPackageName()+"/"+R.raw.new_msg_sound);
//				ringtone = RingtoneManager.getRingtone(appContext, cus_notification);
//
//				if (ringtone == null) {
//					Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//					ringtone = RingtoneManager.getRingtone(appContext, notification);
//
//					if(ringtone == null){
//						HDLog.e(TAG, "cant find ringtone at:" + notification.getPath());
//						return;
//					}
//
//				}
//			}
//
//			if (!ringtone.isPlaying()) {
//				ringtone.play();
//				if (vendor != null && vendor.toLowerCase(Locale.US).contains("samsung")) {
//					Thread ctlThread = new Thread() {
//
//						@Override
//						public void run() {
//							super.run();
//							try {
//								Thread.sleep(3000);
//								if (ringtone.isPlaying()) {
//									ringtone.stop();
//								}
//							} catch (Exception ignored) {
//							}
//
//						}
//
//					};
//					ctlThread.start();
//
//				}
//
//			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * cancel notification
	 */
	public void cancelNotification(){
		if(notificationManager!=null){
			try {
				notificationManager.cancel(notifyID);
			} catch (Exception ignored) {
			}
		}
	}
	
	
	
	
	
	
	
}
